package com.lyf.controller;

import com.lyf.entity.User;
import com.lyf.service.UserService;
import com.mysql.cj.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@CrossOrigin    //跨域
@RequestMapping("user")
public class UserController {

    @Autowired
    private UserService userService;

    //模糊搜索
    @GetMapping("findLike")
    public List<User> findByNameOrPhoneCode(String name, String phoneCode){
        return userService.findByNameOrPhoneCode(name,phoneCode);
    }

    //查询一个
    @GetMapping("findOne")
    public User findOne(String id){
        return userService.findOne(id);
    }

    //查询所有
    @GetMapping("findAll")
    public List<User> findAll(){
        List<User> users = userService.findAll();
        return users;
    }

    //保存用户
    @PostMapping("save")
    public Map<String,Object> save(@RequestBody User user){
        Map<String, Object> map = new HashMap<>();
        try{
            if(StringUtils.isNullOrEmpty(user.getId())){
                userService.save(user);
            } else {
                userService.update(user);
            }
            map.put("success", true);
        }catch (Exception e){
            e.printStackTrace();
            map.put("success",false);
            map.put("msg","保存或更新失败");
        }
        return map;
    }

    //删除用户
    @GetMapping("delete")
    public Map<String,Object> delete(String id){
        Map<String,Object> map = new HashMap<>();
        try{
            userService.delete(id);
            map.put("success",true);
        } catch (Exception e){
            map.put("success",false);
            map.put("msg","删除用户失败");
        }
        return map;
    }

}
